'use strict';
/* egg内置控制器 */
const Controller = require('egg').Controller;

function toInt(str) {
  if (typeof str === 'number') return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}

/* 声明控制器类，并继承与Controller */
class AnimalController extends Controller {
  /* 获取所有数据，声明异步方法*/
  async index() {
    /* ctx与koa中的一样，表示整个应用的上下文环境*/
    const { ctx } = this;
    const { count, rows } = await ctx.model.Animal.findAndCountAll({
      offset: (ctx.pager.current - 1) * ctx.pager.pageSize,
      limit: ctx.pager.pageSize,
    });

    ctx.body = {
      data: rows,
      total: count,
      success: true,
      pageSize: ctx.pager.pageSize,
      current: ctx.pager.current,
    };
  }

  // 查询单个宠物数据
  async show() {
    const { ctx } = this;
    if (!(await ctx.model.Animal.findByPk(toInt(ctx.params.id)))) {
      ctx.body = {
        code: 1001,
        data: '没有查询到该宠物数据！',
      };
      return;
    }
    ctx.body = {
      code: 1000,
      data: await ctx.model.Animal.findByPk(toInt(ctx.params.id)),
    };
  }

  // 添加宠物数据
  async create() {
    const { ctx } = this;
    const { name, age, gender } = ctx.request.body;
    await ctx.model.Animal.create({ name, age, gender });
    ctx.status = 201;
    ctx.body = {
      code: 1000,
      data: '添加成功！',
    };
  }

  // 修改宠物
  async update() {
    const { ctx } = this;
    const id = toInt(ctx.params.id);
    const user = await ctx.model.Animal.findByPk(id);
    const { name, age, gender, userId } = ctx.request.body;
    await user.update({ name, age, gender, userId });
    ctx.body = {
      code: 1000,
      data: '修改成功！',
    };
  }

  //删除宠物
  async destroy() {
    const { ctx } = this;
    const id = toInt(ctx.params.id);
    const user = await ctx.model.Animal.findByPk(id);
    if (!user) {
      ctx.status = 404;
      return;
    }

    await user.destroy();
    ctx.body = {
      code: 1000,
      data: '删除成功！',
    };
  }
}

module.exports = AnimalController;
